package com.haliyoo.adhere.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.haliyoo.adhere.R;
import com.haliyoo.adhere.bean.WeiboBean;
import com.haliyoo.adhere.controller.AdUserConstant;
import com.haliyoo.adhere.controller.Constants;
import com.haliyoo.adhere.controller.OAuthConstant;
import com.haliyoo.adhere.handler.MyCharmHandler;
import com.haliyoo.adhere.util.BitmapGet;
import com.haliyoo.adhere.widget.FaceManager;
import com.haliyoo.adhere.widget.LocalWeiboLayout;
import com.haliyoo.adhere.widget.ProgressBarView;
import com.sina.weibo.view.EditBlogView;
import com.sina.weibo.view.EmotionView;

import weibo4android.User;
import weibo4android.WeiboException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class CreativeDesignActivity extends Activity {
	private static String TAG = "CreativeDesignActivity";
	private int wordsCount = 0;
	private TextView tvWordsCount = null;
	private EditBlogView etText = null;
	private ImageButton ibLocation = null;
	private ImageButton ibCamera = null;
	private ImageButton ibSmile = null;
	private EmotionView expressionGriView = null;
	private boolean isShowSmile = true;
	private ProgressBar pbLocation = null;
	
	/**用来标识请求照相功能的activity*/  
    private static final int CAMERA_WITH_DATA = 3023;  
  
    /**用来标识请求gallery的activity*/  
    private static final int PHOTO_PICKED_WITH_DATA = 3021;  
  
    /**拍照的照片存储位置*/  
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");  
  
    private File mCurrentPhotoFile;//照相机拍照得到的图片
    
    private ImageView ibPicStatus = null;
    private WeiboBean weiboBean = new WeiboBean();
    /**进度条*/
    private ProgressBar pbvWaiting = null;
    private WeiboHandler weiboHandler = new WeiboHandler();
    
    /**当前发送微博的方式：原创，转发，评论*/
    private int publishType = 0;
    private static final int PUBLISH_RAW_WEIBO = 0;
    private static final int PUBLISH_REPOST_WEIBO = 1;
    private static final int PUBLISH_COMMENT_WEIBO = 2;
    /**
     * 当转发时，如果选择上表示同时作为评论
     * 当评论时，如果选择上表示同时发表微博
     * 当原创时，无效
     */
    private boolean extraChecked = false;
    
    private long rawWeiboId = 0;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
    	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newblog2);
		
		etText = (EditBlogView) findViewById(R.id.et_mblog);
		etText.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isShowSmile) {
					/// 加载键盘
					expressionGriView.showKeyboard();
					ibSmile.setImageResource(R.drawable.btn_insert_face);
	
					isShowSmile = !isShowSmile;
				}
			}
		});
		
		/// 页面创建时首先计算剩余字数
		tvWordsCount = (TextView) findViewById(R.id.tv_text_limit);
		wordsCount = 280 - etText.getText().length();
		tvWordsCount.setText(wordsCount + "");
		
		/// 发布按键事件
		Button btPublish = (Button) findViewById(R.id.BUTTON_PUBLISH);
		btPublish.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				/// 显示进度条
				//pbvWaiting.show(getString(R.string.STR_PUBLISHING));
				
				/// 文本
				weiboBean.setText(etText.getText().toString());
				weiboBean.setUser(HallActivity.getUser().getScreenName());
				weiboBean.setTime(Calendar.getInstance().getTime());
				if (HallActivity.getUser() != null) {
					weiboBean.setProfileUrl(HallActivity.getUser().getProfileImageURL().toString());
				}

				if (!weiboBean.getExistImage()) {
					weiboBean.setIcon(null);
				}
				if (!weiboBean.getExistLocation()) {
					weiboBean.setLatitude(0.0);
					weiboBean.setLongitude(0.0);
				}
				
				/// 发送消息发布微博
				Message msg = new Message();
				msg.what = Constants.PUBLISH_WEIBO;
				msg.obj = weiboBean;
				weiboHandler.sendMessage(msg);
			}
		});
		
		/// 保存按钮
		ImageView btSave = (ImageView) findViewById(R.id.iv_save);
		btSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				/// 显示进度条
				//pbvWaiting.show(getString(R.string.STR_SAVING));
				
				/// 文本
				weiboBean.setText(etText.getText().toString());
				weiboBean.setUser(HallActivity.getUser().getScreenName());
				weiboBean.setTime(Calendar.getInstance().getTime());
				if (HallActivity.getUser() != null) {
					weiboBean.setProfileUrl(HallActivity.getUser().getProfileImageURL().toString());
				}

				if (!weiboBean.getExistImage()) {
					weiboBean.setIcon(null);
				}
				if (!weiboBean.getExistLocation()) {
					weiboBean.setLatitude(0.0);
					weiboBean.setLongitude(0.0);
				}

				/// 发送消息发布微博
				Message msg = new Message();
				msg.what = Constants.SAVE_WEIBO;
				msg.obj = weiboBean;
				weiboHandler.sendMessage(msg);
			}
		});
		
		/// 编辑框
		etText.addTextChangedListener(new TextWatcher() {           
            @Override  
            public void onTextChanged(CharSequence s, int start, int before, int count) {  
            	wordsCount = 280 - etText.getText().length();
        		tvWordsCount.setText(wordsCount + "");
            }  
              
            @Override  
            public void beforeTextChanged(CharSequence s, int start, int count,  
                    int after) {                  
            }  
              
            @Override  
            public void afterTextChanged(Editable s) {                                
            }  
        });
		
		/**
		 * 返回键处理
		 */
		ImageButton ibBack = (ImageButton) findViewById(R.id.IMAGE_BUTTON_BACK);
		ibBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();  
			}
		});
		
		/**
		 * 状态栏中的5个按钮
		 */
		
		/**
		 * 定位
		 */
		ibLocation = (ImageButton) findViewById(R.id.ib_insert_location);
		ibLocation.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getLocation();

//	        	latitude = 22.24525;   
//	        	longitude = 114.74445;
//
//				// 下面就是显示照片了
//	        	ibLocationStatus.setVisibility(View.VISIBLE);
//				bExistLocation = true;
			}
		});
		
		/**
		 * 图片
		 */
		ibCamera = (ImageButton) findViewById(R.id.ib_insert_pic);
		ibCamera.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				doPickPhotoAction();
			}
		});
		
		/**
		 * 表情
		 */
		ibSmile = (ImageButton) findViewById(R.id.ib_face_keyboard);
		ibSmile.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isShowSmile) {

					/// 加载表情
					expressionGriView.showEmotionBoard();
					ibSmile.setImageResource(R.drawable.btn_insert_keyboard);
				} else {
					
					/// 加载键盘
					expressionGriView.showKeyboard();
					ibSmile.setImageResource(R.drawable.btn_insert_face);
				}
				
				isShowSmile = !isShowSmile;
			}
		});
		
		/**
		 * 图片状态图标
		 */
		ibPicStatus = (ImageView) findViewById(R.id.iv_insertpic);
		
		/**
		 * 表情显示框
		 */
		expressionGriView = (EmotionView) findViewById(R.id.emotion_view);
		expressionGriView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				/// 在文本中插入图片
                int cursor = etText.getSelectionStart();  
				etText.getText().insert(
						cursor,
						FaceManager.getInstance().getImageByIndex(CreativeDesignActivity.this,
								arg2));
			}
		});
		
		/**
		 *  定位的进度条
		 */
		pbLocation = (ProgressBar) findViewById(R.id.pg_loadlocation);
		
		/**
		 * 等待进度条
		 */
		pbvWaiting = (ProgressBar) findViewById(R.id.pg_loadlocation);
//		if (pbvWaiting == null) {
//			pbvWaiting = new ProgressBarView(CreativeDesignActivity.this);
//		}
		
		/**
		 * 选择按钮
		 */
		LinearLayout llOperation = ((LinearLayout) findViewById(R.id.ll_operation_thesame));
		llOperation.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				CheckBox cbExtra = (CheckBox) findViewById(R.id.rb_comment_sametime);
				if (cbExtra.isChecked()) {
					cbExtra.setChecked(false);
				} else {
					cbExtra.setChecked(true);
				}
				
				extraChecked = cbExtra.isChecked();
			}
		});
		
		/**
		 * 一开始赋值为原创微博
		 * 因为下面会根据判断进行修改
		 */
		publishType = PUBLISH_RAW_WEIBO;
		
		TextView tvTitle = (TextView) findViewById(R.id.TEXT_VIEW_TITLE);
        Intent i = this.getIntent();
        if (!i.equals(null)) {
        	String text = i.getStringExtra("text");
        	String id = i.getStringExtra("id");
            if(id != null){
                initParams(id);
            }
            /// 反馈意见
            else if (text != null) {
            	tvTitle.setText(text);
            }
            /// 转发和评论
            else {
            	String cmd = i.getStringExtra("cmd");
            	rawWeiboId = i.getLongExtra("weiboId", 0);
            	
            	if (rawWeiboId > 0) {
					((LinearLayout) findViewById(R.id.ll_operation_thesame))
							.setVisibility(View.VISIBLE);
					((ImageButton) findViewById(R.id.ib_insert_location))
							.setVisibility(View.GONE);
					((ImageButton) findViewById(R.id.ib_insert_pic))
							.setVisibility(View.GONE);
					((ImageView) findViewById(R.id.iv_save))
							.setVisibility(View.GONE);

					if (cmd.equals("repost")) {
						publishType = PUBLISH_REPOST_WEIBO;
						((TextView) findViewById(R.id.tv_extra_feature_desc))
								.setText(getString(R.string.comment_the_same_time));
						tvTitle.setText(getString(R.string.STR_REPOST));
					} else if (cmd.equals("comment")) {
						publishType = PUBLISH_COMMENT_WEIBO;
						((TextView) findViewById(R.id.tv_extra_feature_desc))
								.setText(getString(R.string.forward_the_same_time));
						tvTitle.setText(getString(R.string.STR_COMMENT));
					}
                }
            }
        }
	}

	private void initParams(String dbId) {
		// TODO Auto-generated method stub
		/// 根据id获取微博
		WeiboBean wb = LocalWeiboLayout.getWeiboBean(dbId);

		/// 显示缩略图
		weiboBean.setExistImage(wb.getExistImage());
		if (weiboBean.getExistImage()) {
			weiboBean.setIcon(wb.getIcon());
			Bitmap tmpBitmap = weiboBean.getIcon();
			Log.i(TAG, "tmp{w:" + tmpBitmap.getWidth() + ", h:"
					+ tmpBitmap.getHeight() + "}");
			ibPicStatus.setVisibility(View.VISIBLE);
			
			Drawable drawable = new BitmapDrawable(BitmapGet.imageZoomByHeight(
					tmpBitmap, Constants.THUMB_IMAGE_HEIGHT));
			ibPicStatus.setBackgroundDrawable(drawable);
			
			Log.i(TAG, "original{w:" + tmpBitmap.getWidth() + ", h:"
					+ tmpBitmap.getHeight() + "}, new{w:"
					+ drawable.getIntrinsicWidth() + ", h:"
					+ drawable.getIntrinsicHeight() + "}");
		}
		
		/// 显示文本
		weiboBean.setText(wb.getText());
		SpannableString ss = FaceManager.getInstance().convertTextToEmotion(this, weiboBean.getText());
		etText.setText(ss);
		
		/// 显示字数
		wordsCount = 280 - etText.getText().length();
		tvWordsCount.setText(getString(R.string.STR_COUNTER) + wordsCount);
		
		/// 显示定位
		weiboBean.setExistLocation(wb.getExistLocation());
		if (weiboBean.getExistLocation()) {
			weiboBean.setLatitude(wb.getLatitude());
			weiboBean.setLongitude(wb.getLongitude());

	        String latLongString = AdUserConstant.getLocation(this, weiboBean.getLatitude(), weiboBean.getLongitude());  
	        
	        Log.i(TAG, latLongString);
	        
            int cursor = etText.getSelectionStart();  
			etText.getText().insert(
					cursor,
					latLongString);
		}
	}

	private void doPickPhotoAction() {
		Context context = CreativeDesignActivity.this;
	
		// Wrap our context to inflate list items using correct theme
		final Context dialogContext = new ContextThemeWrapper(context,
				android.R.style.Theme_Light);
		String cancel = getString(R.string.STR_BACK);
		String[] choices;
		if (weiboBean.getExistImage()) {
			choices = new String[3];
			choices[0] = getString(R.string.STR_CAMERA);  //拍照
			choices[1] = getString(R.string.STR_ALBUM);  //从相册中选择
			choices[2] = getString(R.string.STR_CLEAR);  //清除图片
		} else {
			choices = new String[2];
			choices[0] = getString(R.string.STR_CAMERA);  //拍照
			choices[1] = getString(R.string.STR_ALBUM);  //从相册中选择
		}
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);
	
		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.STR_INSERT_PIC);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:{
							String status=Environment.getExternalStorageState();
							if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							}
							else{
								Toast.makeText(CreativeDesignActivity.this, 
										R.string.STR_ABSENT_SD_CARD, 
										Toast.LENGTH_SHORT).show();
							}
							break;
							
						}
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						case 2:
							clearImage();// 清除图片
							break;
						}
					}
				});
		builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
			
		});
		builder.create().show();
	}

	protected void clearImage() {
		// TODO Auto-generated method stub
		weiboBean.setExistImage(false);
		weiboBean.setIcon(null);
		ibPicStatus.setVisibility(View.GONE);
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			PHOTO_DIR.mkdirs();// 创建照片的存储目录
			mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, R.string.STR_PHOTO_PICKER_NOT_FOUND_TEXT,
					Toast.LENGTH_LONG).show();
		}
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	/**
	 * 用当前时间给取得的图片命名
	 * 
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}

	/**
	 * 请求Gallery程序
	 * 
	 */
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
			intent.setType("image/*");
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, R.string.STR_PHOTO_PICKER_NOT_FOUND_TEXT,
					Toast.LENGTH_LONG).show();
		}
	}

	// 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;

		Bitmap tmpBitmap = null;
		
		switch (requestCode) {
		/// 照相机拍照的结果
		case CAMERA_WITH_DATA: {// 调用Gallery返回的
			tmpBitmap = BitmapGet.getBitmapFromFile(mCurrentPhotoFile);
			// 下面就是显示照片了
			weiboBean.setExistImage(true);
			break;
		}
		
		/// 相册选图的结果
		case PHOTO_PICKED_WITH_DATA: {
			Uri uri = data.getData();
			Log.e("uri", uri.toString());
			ContentResolver cr = this.getContentResolver();
			try {
				tmpBitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
				// 下面就是显示照片了
				weiboBean.setExistImage(true);
			} catch (FileNotFoundException e) {
				Log.e("Exception", e.getMessage(),e);
			}
            break;
		}
		}
		
		/// 显示缩略图
		if (weiboBean.getExistImage()) {
			Log.i(TAG, "tmp{w:" + tmpBitmap.getWidth() + ", h:"
					+ tmpBitmap.getHeight() + "}");
			ibPicStatus.setVisibility(View.VISIBLE);
			
			/// 调整大小，当款凸大于440时调整为440
			if (tmpBitmap.getWidth() > Constants.RAW_IMAGE_WIDTH) {
				Bitmap bitmap = BitmapGet.imageZoomByWidth(tmpBitmap, Constants.RAW_IMAGE_WIDTH);

				Log.i(TAG, "bitmap{w:" + bitmap.getWidth() + ", h:"
						+ bitmap.getHeight() + "}");
				
				weiboBean.setIcon(bitmap);
			} else {
				weiboBean.setIcon(tmpBitmap);
			}
			
			Drawable drawable = new BitmapDrawable(BitmapGet.imageZoomByHeight(
					tmpBitmap, Constants.THUMB_IMAGE_HEIGHT));
			ibPicStatus.setBackgroundDrawable(drawable);
			
			Log.i(TAG, "original{w:" + tmpBitmap.getWidth() + ", h:"
					+ tmpBitmap.getHeight() + "}, new{w:"
					+ drawable.getIntrinsicWidth() + ", h:"
					+ drawable.getIntrinsicHeight() + "}");
		}
	}

	/**
	 * 获取GPS位置
	 */
	public void getLocation() {
		LocationManager locationManager;   
		String serviceName = Context.LOCATION_SERVICE;   
		locationManager = (LocationManager)getSystemService(serviceName);   
		//String provider = LocationManager.GPS_PROVIDER;   
		
		/// 显示进度条
		pbLocation.setVisibility(View.VISIBLE);
		       
		Criteria criteria = new Criteria();   
		criteria.setAccuracy(Criteria.ACCURACY_FINE);   
		criteria.setAltitudeRequired(false);   
		criteria.setBearingRequired(false);   
		criteria.setCostAllowed(true);   
		criteria.setPowerRequirement(Criteria.POWER_LOW);   
		String provider = locationManager.getBestProvider(criteria, true);   
		   
		//Location location = locationManager.getLastKnownLocation(provider);   
		//updateWithNewLocation(location);   
		locationManager.requestLocationUpdates(provider, 1000, 5,   
				new LocationListener() {   
			
		    public void onLocationChanged(Location location) {   
		    	updateWithNewLocation(location);   
		    }   
		    
		    public void onProviderDisabled(String provider){   
		    	updateWithNewLocation(null);   
		    }   
		    
		    public void onProviderEnabled(String provider){ }  
		    
		    public void onStatusChanged(String provider, int status,   
		    Bundle extras){ }   
		});   
	}
	 
	private void updateWithNewLocation(Location location) {   
        String latLongString = null;      

		/// 隐藏进度条
		pbLocation.setVisibility(View.GONE);
		
        if (location != null) {   
        	weiboBean.setLatitude(location.getLatitude());   
        	weiboBean.setLongitude(location.getLongitude());   
        	latLongString = AdUserConstant.getLocation(this, weiboBean.getLatitude(), weiboBean.getLongitude());  
	        
	        Log.i(TAG, latLongString);

            int cursor = etText.getSelectionStart();  
			etText.getText().insert(
					cursor,
					latLongString);
			weiboBean.setExistLocation(true);
        } else {   
        	latLongString = "无法获取地理信息";  
			weiboBean.setExistLocation(false);
        	Toast.makeText(this, latLongString, Toast.LENGTH_LONG).show();
        } 
	}  
	
	class WeiboHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			
			/// 发布微博
			if (msg.what == Constants.PUBLISH_WEIBO) {
				WeiboBean wb = (WeiboBean) msg.obj;

				// / 根据发布方式确定：发布，评论，转发
				if (publishType == PUBLISH_RAW_WEIBO) {
					final long weiboId = AdUserConstant.getInstance().publish(
							CreativeDesignActivity.this, wb);
					if (weiboId > 0) {
						Toast.makeText(CreativeDesignActivity.this,
								R.string.STR_PUBLISH_SUCCESSFULLY,
								Toast.LENGTH_SHORT).show();
						
						/// 上传到AdHere服务器
				        new Thread() {
				            @Override
				            public void run() {
				        		/// 获取数目
				            	if (AdUserConstant.getInstance().post(AdUserConstant.getInstance().user, 
				            			new Long(weiboId).toString(),
				            			AdUserConstant.getInstance().sign) == 1) {
				            		Log.i(TAG, "post to AdHere Server Successfully.");
				            	}
				            }
				        }.start();

						finish();
					} else {
						Toast.makeText(CreativeDesignActivity.this,
								R.string.STR_PUBLISH_FAILED, Toast.LENGTH_SHORT)
								.show();
					}
				} else if (publishType == PUBLISH_REPOST_WEIBO) {
					if (AdUserConstant.getInstance().repost(
							CreativeDesignActivity.this, wb, rawWeiboId,
							extraChecked)) {
						Toast.makeText(CreativeDesignActivity.this,
								R.string.new_forward_success,
								Toast.LENGTH_SHORT).show();

						finish();
					} else {
						Toast.makeText(CreativeDesignActivity.this,
								R.string.new_forward_failed, Toast.LENGTH_SHORT)
								.show();
					}
				} else if (publishType == PUBLISH_COMMENT_WEIBO) {
					if (AdUserConstant.getInstance().comment(
							CreativeDesignActivity.this, wb, rawWeiboId)) {
						Toast.makeText(CreativeDesignActivity.this,
								R.string.new_comment_succeed,
								Toast.LENGTH_SHORT).show();

						finish();
					} else {
						Toast.makeText(CreativeDesignActivity.this,
								R.string.new_comment_fail, Toast.LENGTH_SHORT)
								.show();
					}
				}

				// / 隐藏进度条
				// pbvWaiting.hide();
			}
			// / 保存微博
			else if (msg.what == Constants.SAVE_WEIBO) {
				WeiboBean wb = (WeiboBean) msg.obj;
				// / 保存到数据库
				if (AdUserConstant.save(CreativeDesignActivity.this, wb)) {
					Toast.makeText(CreativeDesignActivity.this,
							R.string.STR_SAVE_SUCCESSFULLY, Toast.LENGTH_SHORT)
							.show();

					finish();
				} else {
					Toast.makeText(CreativeDesignActivity.this,
							R.string.STR_SAVE_FAILED, Toast.LENGTH_SHORT)
							.show();
				}
			}

			super.handleMessage(msg);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (expressionGriView.isShown()) {
				expressionGriView.hide();
				ibSmile.setImageResource(R.drawable.btn_insert_face);
	
				return false;
			}
		}
		
		return super.onKeyDown(keyCode, event);
	}

}
